package com.beetobe.callib.event;

import java.io.IOException;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

import com.beetobe.callib.CalendarLibHelper;
import com.beetobe.callib.test.EventListActivity;
import com.google.api.services.calendar.model.Event;

public class AsyncUpdateEvent extends AsyncTask<Void, Void, Void> {

	private final EventListActivity EventListActivity;
	private final ProgressDialog dialog;
	private final int eventIndex;
	private final String calendarId;
	private final String eventId;
	
	private com.google.api.services.calendar.Calendar client;

	public AsyncUpdateEvent(EventListActivity EventListActivity, String calendarId, int eventIndex) {
		this.EventListActivity = EventListActivity;
//		this.calendarIndex = calendarIndex;
//		this.caledndarId = EventListActivity.calendars.get(calendarIndex).id;
		this.calendarId = calendarId;
		this.eventIndex = eventIndex;
		this.eventId = EventListActivity.eventList.get(eventIndex).id;
		client = CalendarLibHelper.client;
		dialog = new ProgressDialog(EventListActivity);
	}

	@Override
	protected void onPreExecute() {
		dialog.setMessage("Updating event...");
		dialog.show();
	}

	@Override
	protected Void doInBackground(Void... arg0) {
			Log.w("AsyncUpdateEvent : ", "still alive");
		try {
			Event event = client.events().get(calendarId, eventId).execute();
			event.setSummary("Edited event");
			Event updatedEvent = client.events().update(calendarId, event.getId(), event).execute();
			
			EventListActivity.eventList.remove(eventIndex);
			EventInfo info = new EventInfo(updatedEvent.getId(),updatedEvent.getSummary());
			EventListActivity.eventList.add(info);
		} catch (IOException e) {
			EventListActivity.handleGoogleException(e);
		} finally {
			EventListActivity.onRequestCompleted();
		}
		return null;
	}

	@Override
	protected void onPostExecute(Void result) {
		dialog.dismiss();
		EventListActivity.refresh();
	}
}